"use strict";

const path = require("path");
const { BrowserWindow } = require("electron");
const { getMainWindow } = require("ee-core/electron");
const { isDev, getBaseDir } = require("ee-core/ps");
const { logger } = require("ee-core/log");

// 引入窗口调整相关函数
const { getHeadDisplayScript, getContentSizeScript } = require("../preload/softmanager");

/**
 * 窗口服务类
 */
class WindowService {
  constructor() {
    this.windows = {};
  }

  /**
   * 创建窗口
   */
  createWindow(args) {
    const { windowName, contentUrl, showHead = false } = args;
    const mainWindow = getMainWindow();

    const opt = {
      title: "提示",
      width: 500,
      height: 600,
      center: true,
      autoHideMenuBar: true,
      minimizable: false,
      maximizable: false,
      resizable: false,
      backgroundColor: "#fff",
      webPreferences: {
        contextIsolation: false,
        nodeIntegration: true,
        enablePreferredSizeMode: true,
      },
      frame: true,
      show: false,
      icon: path.join(getBaseDir(), "public", "images", "logo-32.png"),
      useContentSize: true,
      fullscreenable: false,
      modal: true,
      parent: mainWindow,
    };

    const win = new BrowserWindow(opt);
    const winContentsId = win.webContents.id;

    // 拦截导航事件
    win.webContents.on("will-navigate", (event, url) => {
      if (url == "eap:/") {
        event.preventDefault();
        this.closeAllWindows();
      }
    });

    // 页面加载完成后调整窗口大小
    const handleContentReady = async () => {
      try {
        await this._adjustWindowSize(win, showHead);
        win.show();
      } catch (err) {
        logger.error("handleContentReady error:", err);
        win.show();
      }
    };

    win.webContents.on("did-finish-load", handleContentReady);
    win.loadURL(contentUrl);

    if (isDev()) {
      win.webContents.openDevTools();
    }

    this.windows[windowName] = win;
    return winContentsId;
  }

  /**
   * 调整窗口大小
   */
  async _adjustWindowSize(win, showHead) {
    try {
      // 设置头部显示状态
      await win.webContents.executeJavaScript(getHeadDisplayScript(showHead));

      // 获取内容实际尺寸
      const contentSize = await win.webContents.executeJavaScript(getContentSizeScript());

      if (!contentSize) {
        logger.warn("[adjustWindowSize] 未找到有效内容元素");
        return;
      }

      // 调整窗口大小
      const { winWidth, winHeight } = contentSize;
      win.setContentSize(winWidth, winHeight);
      win.center();

      logger.info("[adjustWindowSize] 窗口调整完成", {
        currentSize: win.getContentSize(),
      });
    } catch (err) {
      logger.error("[adjustWindowSize] 调整失败", err);
    }
  }

  /**
   * 关闭指定窗口
   */
  closeWindow(windowName) {
    if (this.windows[windowName]) {
      this.windows[windowName].close();
      delete this.windows[windowName];
    }
  }

  /**
   * 关闭所有窗口
   */
  closeAllWindows() {
    Object.keys(this.windows).forEach((windowName) => {
      this.closeWindow(windowName);
    });
  }
}

module.exports = {
  WindowService,
  windowService: new WindowService(),
};